import { getUserInfo, login } from '@/api/user'
import { constantRoutes, resetRouter } from '@/router'
import { getToken, removeToken, setToken } from '@/utils/auth'

const state = {
  token: getToken(), // 从本地存储中获取token
  userInfo: {}, // 存储用户信息
  routes: constantRoutes // 静态路由的数组
}

const mutations = {
  setToken(state, token) {
    // 将token存储到vuex中 (vuex的数据在内存中, 刷新会丢失)
    state.token = token
    // 将token存储到cookie缓存中
    setToken(token)
  },
  removeToken(state) {
    // 删除vuex的token
    state.token = null
    removeToken()
  },
  setUserInfo(state, userInfo) {
    state.userInfo = userInfo
  },
  setRoutes(state, newRoutes) {
    state.routes = [...constantRoutes, ...newRoutes]
  }
}

const actions = {
  async login(context, data) {
    // 1. 发送登录请求 TODO
    // 2. 获取token
    const token = await login(data)
    // 3. 提交mutation
    context.commit('setToken', token)
  },
  async getUserInfo(context) {
    // 发请求获取用户信息
    const result = await getUserInfo()
    context.commit('setUserInfo', result)
    return result
  },
  logout(context) {
    context.commit('removeToken') // 删除token
    context.commit('setUserInfo', {}) // 删除用户信息
    // 重置路由
    resetRouter()
  }
}

const getters = {}

export default {
  namespaced: true, // 开启命名空间
  state,
  mutations,
  actions,
  getters
}
